package cuongnh.project.japanesediary.vocabulary.ui.view.action.menucontribution.category;

import java.util.Set;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import cuongnh.project.japanesediary.vocabulary.common.CommonServices;
import cuongnh.project.japanesediary.vocabulary.model.Category;
import cuongnh.project.japanesediary.vocabulary.ui.view.CategoryListView;

public class SynchronizeCategoryAction implements IViewActionDelegate {

	public static final String ID = "cuongnh.project.japanesediary.vocabulary.action.SynchronizeCategory";

	protected IViewPart m_view;

	private CommonServices commonServices;

	private Category category;

	private TreeViewer treeViewer;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		m_view = view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		// 履歴ビュー更新
		CategoryListView view = (CategoryListView) m_view
				.getAdapter(CategoryListView.class);
		commonServices = view.getCommonServices();
		category = view.getSelectedCategory();
		if (category != null) {
			category = commonServices.getCategoryDao()
					.getCategoryWithSubCategories(category.getCategoryId());
			Set<Category> subCategories = category.getSubCategories();
			for (Category subCategory : subCategories) {
				synchronize(category, subCategory);
			}

			view.refresh();
		}
	}

	private void synchronize(Category parentCategory, Category childCategory) {
		childCategory = commonServices.getCategoryDao()
				.getCategoryWithAllLazies(childCategory.getCategoryId());
		Set<Category> subCategories = childCategory.getSubCategories();
		if (!subCategories.isEmpty()) {
			for (Category category : subCategories) {
				synchronize(childCategory, category);
			}
		}

		parentCategory = commonServices.getCategoryDao()
				.getCategoryWithAllLazies(parentCategory.getCategoryId());
		parentCategory.getVocabularies()
				.addAll(childCategory.getVocabularies());
		parentCategory.getKanjis().addAll(childCategory.getKanjis());
		parentCategory.getGrammars().addAll(childCategory.getGrammars());
		parentCategory.getSentences().addAll(childCategory.getSentences());

		commonServices.getCategoryDao().update(parentCategory);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
